/*********************************************************************************
 *      Copyright:  (C) 2025 TBW
 *                  All rights reserved.
 *
 *       Filename:  socket_connected.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(26/05/25)
 *         Author:  
 *      ChangeLog:  1, Release initial version on "26/05/25 15:02:40"
 *                 
 ********************************************************************************/

int socket_connected(socket_info_t *socket_info)
{


    /*
	 *解决不能判断连接断开问题*
	 *
	 *
	 *
    // 方法1：检查套接字错误状态
    int error_code = 0;
    socklen_t len = sizeof(error_code);

    if (getsockopt(socket_info->fd, SOL_SOCKET, SO_ERROR, &error_code, &len) == -1 ||
        error_code != 0) {
        return -1;  // 连接已断开
    }

    // 方法2：非阻塞读取测试
    fd_set readfds;
    FD_ZERO(&readfds);
    FD_SET(socket_info->fd, &readfds);

    struct timeval timeout = {0, 0};  // 非阻塞
    if (select(socket_info->fd + 1, &readfds, NULL, NULL, &timeout) > 0 &&
        FD_ISSET(socket_info->fd, &readfds)) {

        char buf[1];
        int n = recv(socket_info->fd, buf, sizeof(buf), MSG_PEEK);

        if (n == 0) {
            return -1;  // 连接已关闭
        }
    }

    return 0;  // 连接正常
    */
    int                 error_code = 0;
    socklen_t           len = sizeof(error_code);

    if(!socket_info)
    {
        log_error("invalid argument\n");
        goto out;
    }

    if( socket_info->fd < 0)//first connect failure
    {
        log_error("connect break\n");
        goto out;
    }

    // 获取套接字错误状态
    if (getsockopt(socket_info->fd, SOL_SOCKET, SO_ERROR, &error_code, &len) == -1)
    {
        log_error("getsockopt failed:%s\n", strerror(errno));
        goto out;
    }

    // 重置错误状态
    if (error_code != 0)
    {
        errno = error_code;  // 设置 errno 以便使用 perror()
        log_error("Socket error:%s\n", strerror(errno));
        goto out;
    }

    socket_info->status = 1;//并不需要靠该变量的值去判断连接是否断开,可删？
                            //靠fd的值，getsockopt函数
    log_debug("continue! ");
    return socket_info->status;  // 连接正常
out:
    socket_info->status = -1;
    log_debug("continue! ");
    return socket_info->status;
}

